document.addEventListener('DOMContentLoaded', function() {
    const registerForm = document.getElementById('registerForm');
    const usernameInput = document.getElementById('username');
    const emailInput = document.getElementById('email');
    const passwordInput = document.getElementById('password');
    const confirmPasswordInput = document.getElementById('confirmPassword');
    const phoneInput = document.getElementById('phone');
    const agreeTermsCheckbox = document.getElementById('agreeTerms');
    const registerButton = registerForm.querySelector('.register-btn');
    const messageBox = document.querySelector('.message-box');
    const messageText = messageBox.querySelector('span');
    const passwordStrength = document.querySelector('.password-strength');
    const strengthBar = passwordStrength.querySelector('.strength-bar');
    const strengthText = passwordStrength.querySelector('.strength-text');

    // 密码显示切换
    document.querySelectorAll('.toggle-password').forEach(button => {
        button.addEventListener('click', function() {
            const input = this.parentElement.querySelector('input');
            const type = input.type === 'password' ? 'text' : 'password';
            input.type = type;
            this.querySelector('i').classList.toggle('fa-eye');
            this.querySelector('i').classList.toggle('fa-eye-slash');
        });
    });

    // 密码强度检查
    function checkPasswordStrength(password) {
        let strength = 0;
        if (password.length >= 8) strength++;
        if (password.match(/[a-z]/) && password.match(/[A-Z]/)) strength++;
        if (password.match(/\d/)) strength++;
        if (password.match(/[^a-zA-Z\d]/)) strength++;

        switch(strength) {
            case 0:
            case 1:
                return { strength: 'weak', text: '弱' };
            case 2:
            case 3:
                return { strength: 'medium', text: '中' };
            case 4:
                return { strength: 'strong', text: '强' };
        }
    }

    // 更新密码强度显示
    function updatePasswordStrength(password) {
        if (!password) {
            passwordStrength.style.display = 'none';
            return;
        }

        passwordStrength.style.display = 'block';
        const result = checkPasswordStrength(password);
        passwordStrength.className = 'password-strength strength-' + result.strength;
        strengthText.textContent = '密码强度：' + result.text;
    }

    // 表单验证函数
    function validateUsername(username) {
        return username.length >= 3;
    }

    function validateEmail(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    }

    function validatePassword(password) {
        return password.length >= 6;
    }

    function validatePhone(phone) {
        if (!phone) return true; // 手机号是选填的
        const re = /^1[3-9]\d{9}$/;
        return re.test(phone);
    }

    function showError(input, message) {
        const errorText = input.parentElement.querySelector('.error-text');
        errorText.textContent = message;
        errorText.style.display = 'block';
        input.style.borderBottomColor = '#c62828';
    }

    function clearError(input) {
        const errorText = input.parentElement.querySelector('.error-text');
        errorText.style.display = 'none';
        input.style.borderBottomColor = '';
    }

    function showMessage(message, isError = true) {
        messageBox.style.display = 'flex';
        messageText.textContent = message;
        messageBox.className = `message-box ${isError ? 'error' : 'success'}`;
    }

    function setLoading(isLoading) {
        const spinner = registerButton.querySelector('.spinner');
        const buttonText = registerButton.querySelector('span');
        registerButton.disabled = isLoading;
        spinner.style.display = isLoading ? 'block' : 'none';
        buttonText.style.opacity = isLoading ? '0' : '1';
    }

    // 输入事件监听
    usernameInput.addEventListener('input', () => clearError(usernameInput));
    emailInput.addEventListener('input', () => clearError(emailInput));
    passwordInput.addEventListener('input', () => {
        clearError(passwordInput);
        updatePasswordStrength(passwordInput.value);
    });
    confirmPasswordInput.addEventListener('input', () => clearError(confirmPasswordInput));
    phoneInput.addEventListener('input', () => clearError(phoneInput));

    // 服务条款和隐私政策链接处理
    document.querySelector('.terms-link').addEventListener('click', function(e) {
        e.preventDefault();
        alert('服务条款页面即将上线');
    });

    document.querySelector('.privacy-link').addEventListener('click', function(e) {
        e.preventDefault();
        alert('隐私政策页面即将上线');
    });

    // 表单提交处理
    registerForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const username = usernameInput.value.trim();
        const email = emailInput.value.trim();
        const password = passwordInput.value.trim();
        const confirmPassword = confirmPasswordInput.value.trim();
        const phone = phoneInput.value.trim();
        let hasError = false;

        // 清除之前的错误
        clearError(usernameInput);
        clearError(emailInput);
        clearError(passwordInput);
        clearError(confirmPasswordInput);
        clearError(phoneInput);
        messageBox.style.display = 'none';

        // 验证用户名
        if (!username) {
            showError(usernameInput, '请输入用户名');
            hasError = true;
        } else if (!validateUsername(username)) {
            showError(usernameInput, '用户名至少需要3个字符');
            hasError = true;
        }

        // 验证邮箱
        if (!email) {
            showError(emailInput, '请输入邮箱地址');
            hasError = true;
        } else if (!validateEmail(email)) {
            showError(emailInput, '请输入有效的邮箱地址');
            hasError = true;
        }

        // 验证密码
        if (!password) {
            showError(passwordInput, '请输入密码');
            hasError = true;
        } else if (!validatePassword(password)) {
            showError(passwordInput, '密码至少需要6个字符');
            hasError = true;
        }

        // 验证确认密码
        if (!confirmPassword) {
            showError(confirmPasswordInput, '请确认密码');
            hasError = true;
        } else if (password !== confirmPassword) {
            showError(confirmPasswordInput, '两次输入的密码不一致');
            hasError = true;
        }

        // 验证手机号（如果填写了）
        if (phone && !validatePhone(phone)) {
            showError(phoneInput, '请输入有效的手机号码');
            hasError = true;
        }

        // 验证服务条款
        if (!agreeTermsCheckbox.checked) {
            showMessage('请阅读并同意服务条款和隐私政策');
            hasError = true;
        }

        if (hasError) return;

        // 开始注册流程
        setLoading(true);

        try {
            const response = await fetch('/api/users/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username,
                    email,
                    password,
                    phone: phone || undefined
                })
            });

            const data = await response.json();

            if (data.success) {
                showMessage('注册成功！正在跳转到登录页面...', false);
                
                // 延迟跳转到登录页面
                setTimeout(() => {
                    window.location.href = '/login.html';
                }, 2000);
            } else {
                showMessage(data.message || '注册失败，请稍后重试');
            }
        } catch (error) {
            console.error('注册错误:', error);
            showMessage('注册失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    });
});
